package Servlet;

import pojo.user;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = {"/user"})//注解名称，跟在浏览器的后面
public class userServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        List<user> users=new ArrayList<>();

       //jdbc进入数据库  查询
        try
        {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接(url,user,password)
            String url = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
            Connection con = DriverManager.getConnection(url, "root", "Aa123456");

            //3.写sql语句
            String sql="select * from sys_user";

            //4.预编译sql
            PreparedStatement pst = con.prepareStatement(sql);

            //5.有参数设置参数

            //6.执行sql语句
            ResultSet resultSet = pst.executeQuery();

            //7.遍历结果集
            while(resultSet.next()){
                user user=new user();//创建一个新的user
                user.setId(resultSet.getInt(1));
                user.setName(resultSet.getString(2));
                user.setPassword(resultSet.getString(3));
                users.add(user);
            }

            //8.关资源
            resultSet.close();
            pst.close();
            con.close();
            //把集合中的数据存储到作用域中
            req.setAttribute("users",users);
            req.getRequestDispatcher("/user.jsp").forward(req,resp);
        }
        catch (ClassNotFoundException e)
        {
            throw new RuntimeException(e);
        } catch (SQLException e)
        {
            throw new RuntimeException(e);
        }

    }
}
